#include "stdafx.h"
#include "View.h"

namespace Cinetic
{
    void View::on_game_object_added( std::weak_ptr<GameObject> go )
    {
        auto goptr = go.lock();
        for (auto it = goptr->component_begin(); it != goptr->component_end(); it++) {
            on_component_added(go, *it);
        }
    }

    void View::on_game_object_removed( std::weak_ptr<GameObject> go )
    {
        auto goptr = go.lock();
        for (auto it = goptr->component_begin(); it != goptr->component_end(); it++) {
            on_component_removed(go, *it);
        }
    }

    void View::on_component_added( std::weak_ptr<GameObject> go, std::weak_ptr<Component> c )
    {
        auto representation = create_representation(c);
        if (representation) {
            m_representation_list.push_back(representation);
        }
    }

    void View::on_component_removed( std::weak_ptr<GameObject> go, std::weak_ptr<Component> c )
    {
        auto representation = get_representation(c);
        if (representation) {
            auto it = std::find(m_representation_list.begin(), m_representation_list.end(), representation);
            m_representation_list.erase(it);
        }
    }

    std::shared_ptr<Representation> View::get_representation( std::weak_ptr<Object> g )
    {
        auto search_method = [&](const std::shared_ptr<Representation>& r)->bool {
            return r->model().lock() == g.lock();
        };

        auto it = std::find_if(m_representation_list.begin(), m_representation_list.end(), search_method);
        if (it != m_representation_list.end()) {
            return *it;
        }

        return nullptr;
    }
}